<?php
/**
 * Created by PhpStorm.
 * User: Guangpeng Chen
 * Date: 11-6/2014
 * Time: 15:00
 */

include 'config.inc.php';
/* 产品抓取资料表
产品如果有在产品库，更新产品库关联
否则插入，插入返回PID
账户验证格式:md5(账户+md5(密码))
返回(数据流)格式：josn 二维数组 array('account'=>600000,'mode'=>1 //0插入1更新,pids=>array(11=>'更新时间',21...),'pwd'=>'')
输出PID格式：一维数组 票付通PID=>远端产品ID
*/
$request_data = file_get_contents("php://input");
//echo $request_data;
if (empty($request_data)) {
    exit('empty request data');
}

//TODO::Let's log it first.
ProductApi::writeLog( $data_now .'|'.$request_data, 'request_data');
//exit;
$json_array = json_decode($request_data);
//print_r($json_array);
$xml        = base64_decode($json_array->data);
//echo $xml;exit;
$xml_arr    = simplexml_load_string($xml);
$header     = $xml_arr->header;
$body       = $xml_arr->body;
$account    = (string)$header->account;
$verifyCode = (string)$header->verifycode;
$product = new ProductApi($pdo);
//账户验证,并获取供应商的id，即pft_member表的ID
$apply_did = $product->Auth($account, $verifyCode);
//TODO::判断是更新还是插入
$remote_id = (int)$body->product_id;//对方平台产品id
ProductApi::$remoteId = $remote_id;//设置对方平台产品ID

if ($apply_did===false) {
    ProductApi::writeLog(ProductApi::now()."|Access Denied with account:{$account},verifyCode:{$verifyCode}", 'access_deny.log');
    ProductApi::Response('401');
}
$chkRet = $product->ChkUpdateOrInsert($account, $remote_id);

//TODO::写数据到uu_land表
$landInfo   = array();//uu_land表数据
$extInfo    = array();
$ticketInfo = array();//uu_jq_ticket表数据

if (!$body->account) {
    ProductApi::Response('106');
}
if (empty($body->product_name)) {
    ProductApi::Response('107');
}
$landInfo['title']    = safetxt((string)$body->product_name);
$landInfo['tel']      = (string)$body->tel;
$landInfo['jtype']    = (string)$body->product_level;
$landInfo['opentime'] = (string)$body->opentime;

$ptype = (string)$body->product_type;
if (!in_array($ptype, array('A','B','C','F'))) {
    ProductApi::Response('105');
}
if ( $ptype== 'B') {
    if (empty($body->start_city) || empty($body->end_city)) {
        ProductApi::Response('126');//126：出发地/目的地 产品类型为线路时，必填
    }
    $extInfo['startplace']      = (string)$body->start_city;//
    $extInfo['endplace']        = (string)$body->end_city;//

    $landInfo['runtime'] = (string)$body->start_city . '|'.(string)$body->end_city;
    $new_ass = array();
    foreach ($body->ass_stations->ass_station as $ass_station) {
        $new_ass[] = "集合地点:" . $ass_station->assembling_place 
                  . ",集合时间:" . $ass_station->assembling_time
                  . ",导游手机:" . $ass_station->guide_telphone;
    }
    if (!count($new_ass)) {
        ProductApi::Response('128');//126：出发地/目的地 产品类型为线路时，必填
    }
    $extInfo['ass_station']  = serialize($new_ass);
    if (empty($body->journey_days) || $body->journey_days<0) {
        ProductApi::Response('127');//127：游玩天数 产品类型为线路时，必填
    }
    $extInfo['rdays']        = (int)$body->journey_days;
    $series_model            = explode('|', (string)$body->series_model);
    $extInfo['series_model'] = $series_model[0] .'{fck_date}' . $series_model[1];
}
elseif($ptype == 'F') {
    //套票[{"pid":"18","num":"1","lid":"16","aid":"4"}]
    $packages = array();
    $pft_pids = array();
    foreach ($body->include_ticket->ticket as $ticket) {
        $packages[(int)$ticket->id]['num'] = (int)$ticket->num ;
    }
    if (!count($packages)) {
        ProductApi::Response('101');
    }
    $sql_get_pft_pid = "SELECT pid,remoteid FROM get_Product_Fromt_Lib WHERE remoteid IN(".implode(',', $pids).")";
    $stmt = $pdo->prepare($sql_get_pft_pid);
    $stmt->execute();
    while($row=$stmt->fetch(PDO::FETCH_ASSOC)) {
        $pft_pids[] = $row['pid'];
        $packages[$row['remoteid']]['pid'] = $row['pid'];
    }
    $stmt = null;
    unset($stmt);
    if (!count($pft_pids)) {
        ProductApi::Response('102');
    }
    $sql_get_pft_lid = "SELECT contact_id,apply_did FROM uu_products WHERE id IN(".implode(',', $pft_pids).")";
    $stmt = $pdo->prepare($sql_get_pft_pid);
    $stmt->execute();
    while($row=$stmt->fetch(PDO::FETCH_ASSOC)) {
        $packages[$row['remoteid']]['lid'] = $row['contact_id'];
        $packages[$row['remoteid']]['aid'] = $row['apply_did'];
    }
    $landInfo['attribute'] = json_encode(array_values($packages));
    $stmt = null;
    unset($stmt);
    unset($packages);
    unset($pft_pids);
}
//要特殊处理
if (!empty($body->city)) {
    $areaArr = explode('|', (string)$body->city);
    $sql = "SELECT area_id FROM area WHERE area_name LIKE '%{$areaArr[0]}%' LIMIT 1";
    $stmt = $pdo->prepare($sql);
    $stmt->execute();
    $province = $stmt->fetchColumn(0);
    $sql = "SELECT area_id FROM area WHERE area_name LIKE '%{$areaArr[1]}%' LIMIT 1";
    $stmt = $pdo->prepare($sql);
    $stmt->execute();
    $city = $stmt->fetchColumn(0);
    $sql = "SELECT area_id FROM area WHERE area_name LIKE '%{$areaArr[2]}%' LIMIT 1";
    $stmt = $pdo->prepare($sql);
    $stmt->execute();
    $zone = $stmt->fetchColumn(0);
    $landInfo['area']      = "{$province}|{$city}|{$zone}";
}

 if (empty($body->address)) {
     ProductApi::Response('125');//详细地址为空
 }
 $landInfo['address']   = safetxt( (string)$body->address);
 $landInfo['jqts']      = safetxt( (string)$body->notice);
 $landInfo['bhjq']      = safehtml( (string)$body->details );
 $landInfo['jtzn']      = safetxt( (string)$body->traffic);
 $landInfo['imgpath']   = safetxt( (string)$body->img_path);
 $landInfo['addtime']   = ProductApi::now();
 $landInfo['p_type']    = $ptype;
 
 $delay_hour            = floor((int)$body->use_delay_minute / 60);
 $delay_min             = (int)$body->use_delay_minute % 60;
 $landInfo['delaytime'] = $delay_hour . '|' . $delay_min;
 
 $landInfo['status']    = 1;
 $landInfo['apply_did'] = $apply_did;

//TODO::写数据到uu_jq_ticket表


$ticketInfo['title']             = safetxt( (string)$body->ticket_name );
if (!$ticketInfo['title']) {
    ProductApi::Response('103');
}
$ticketInfo['tprice']            = (float)$body->market_price;
$ticketInfo['getaddr']           = safetxt( (string)$body->get_ticket_info );

if (!$ticketInfo['getaddr']) {
    ProductApi::Response('104');//104:取票信息不能为空
}
if ( !in_array((int)$body->payment_type, array(0,1)) ) {
    ProductApi::Response('108');
}
$ticketInfo['pay']               = (int)$body->payment_type;
$ticketInfo['storage']           = (int)$body->total_storage;
$ticketInfo['cancel_auto_onMin'] = (int)$body->auto_cancel_minute;

if ( $ptype!='F' && !in_array((int)$body->use_delay_type, array('0','1','2','3')) ) {
    ProductApi::Response('109');
}
$ticketInfo['delaytype']         = (int)$body->use_delay_type;
if ( ($body->use_delay_type==1 || $body->use_delay_type==2) && !$body->use_delay_days) {
    ProductApi::Response('110');
}
$ticketInfo['delaydays']         = (int)$body->use_delay_days;
if ($body->use_delay_type==3 && !$body->use_deadline) {
    ProductApi::Response('111');
}

$ticketInfo['cancel_auto_onMin'] = (string)$body->use_deadline;
$ticketInfo['order_end']         = (int)$body->auto_cancel_minute;
$ticketInfo['ddays']             = (int)$body->book_early_days;
$recharge = (float)$body->refundcharge;
if (!is_numeric($recharge) || $recharge>100) {
    ProductApi::Response('112');
}
$ticketInfo['reb']               = (float)$body->refundcharge;//退款手续费(%)
$ticketInfo['buy_limit_low']     = (int)$body->buy_min_num;
$ticketInfo['buy_limit_up']      = (int)$body->buy_max_num;
$ticketInfo['apply_did']         = $apply_did;

//TODO::写数据到票类属性扩展表

$extInfo['dhour']           = (int)$body->book_deadline;//提前下单截止日具体时间

$extInfo['v_ID_support']    = (int)$body->idcard_verify;//提前下单截止日具体时间
if ( !empty($body->verify_start_time) ) {

    if (empty($body->verify_end_time)) {
        ProductApi::Response('129');//验证时间错误，必须设置截止验证时间。
    }
    $extInfo['v_time_limit']= (string)$body->verify_start_time . '|'
        . (string)$body->verify_end_time;
}


//TODO::处理价格
$Y_m_d = date('Y-m-d');
$priceArr = array();
if (!count($body->price_array->price)) {
    ProductApi::Response('113');
}
foreach ( $body->price_array->price  as $price) {
    if (empty($price->start_date) || empty($price->end_date)) {
        ProductApi::Response('121');//121:价格有效日期为空
    }
    $enddate = (string)$price->end_date;
    if($enddate < $Y_m_d) continue;//过滤今天之前的价格

    if ((int)$price->retail_price<(int)$price->supply_price) {
        ProductApi::Response('120');//120：零售价必须大于供货价
    }

    if (empty($price->valid_week)) {
        $ondays = '0,1,2,3,4,5,6';
    }
    else {
        $ondays_arr = explode(',', (string)$price->valid_week);
        foreach ($ondays_arr as $week) {
            if ($week > 7 || $week <0) {
                ProductApi::Response('130');//130：价格有效星期格式错误
            }
        }
    }
    $priceArr[] = array(
        'price_id'   => (int)$price->price_id,
        'start_date' => (string)$price->start_date,
        'end_data'   => $enddate,
        'pg'         => (int)$price->supply_price,
        'pl'         => (int)$price->retail_price,
        'ondays'     => (string)$price->valid_week,
        'ptype'      => (int)$price->ptype,
        'storage'    => (int)$price->storage,
    );
}

//print_r($landInfo);
//print_r($ticketInfo);
//print_r($extInfo);
//print_r($priceArr);
//exit;
if ($chkRet===false) {
    $handlerMode = 0;
    //插入
    $landInsertRes   = $product->AddProduct($landInfo);
    if ($landInsertRes===1) {
        ProductApi::Response('118');
    }
    if ($landInsertRes===2) {
        ProductApi::Response('119');
    }
    if ($landInsertRes===3) {
        ProductApi::Response('117');
    }
    if ($landInsertRes===4) {
        ProductApi::Response('114');
    }
    $lid = $landInsertRes['lastid'];
    //TODO::写数据到uu_jq_ticket表
//    $ticketInfo = array();//uu_jq_ticket表数据
    $ticketInfo['landid']       = $landInsertRes['lastid'];
    $ticketInfo['apply_did']    = $apply_did;
    $ticketInsertRet = $product->SaveTicket($ticketInfo);
    if ($ticketInsertRet===false) {
        ProductApi::Response('115');//保存票类属性失败
    }
    $pid = $ticketInsertRet['pid'];
    //TODO::写数据到票类属性扩展表
    $extInfo['pid'] = $pid;
    $extInfo['tid'] = $ticketInsertRet['lastid'];
    $extInfo['lid'] = $landInsertRes['lastid'];
    $ticket_ext = $product->ProductExt($extInfo);
    if ($ticket_ext === false ) {
        ProductApi::Response('116');
    }
    //TODO::添加价格
    foreach ($priceArr as $pc) {
        $priceRes  = ProductApi::soap()->In_Dynamic_Price_Merge($pid, $pc['start_date'],$pc['end_data'],
            $pc['pg'], $pc['pl'], $pc['ptype'], $mode, $pc['price_id'], '', $pc['ondays'], $pc['storage']);
        if ($priceRes==142) {
            ProductApi::Response('122');//122：一个票种多个价格有效期日期重叠
        }
        elseif ($priceRes!=100) {
            ProductApi::writeLog(ProductApi::now()."|价格插入失败.返回{$priceRes}",
                'logs/price.err');
            ProductApi::Response('100');
        }
    }
}
elseif (is_array($chkRet)) {
    //更新
    $handlerMode = 1;
    $landUpdateRes   = $product->UpdateScenery($landInfo, $chkRet['lid']);
    if ($landUpdateRes === false) {
        ProductApi::Response('114');//114：保存产品属性失败

    }
    $lid = $chkRet['lid'];
    $ticketInfo['landid']       = $chkRet['lid'];
    $ticketInsertRet = $product->SaveTicket($ticketInfo, $chkRet['tid']);
    if ($ticketInsertRet === false) {
        ProductApi::Response('115');
    }
    $pid = $ticketInsertRet['pid'];
    $tid = $ticketInsertRet['lastid'];

    $ticket_ext = $product->ProductExt($extInfo, $chkRet['lf_id']);
    if ($ticket_ext === false) {
        ProductApi::Response('116');
    }
    //TODO::添加价格
   foreach ($priceArr as $pc) {
       //TODO::判定这个价格是否已经写入到数据库
       $sql_get_priceid = <<<SQL
SELECT id FROM uu_product_price WHERE pid=$pid AND rid={$pc['price_id']} LIMIT 1
SQL;
       $stmt = $pdo->prepare($sql_get_priceid);
       $stmt->execute();
       $price_id = $stmt->fetchColumn(0);
       if ($price_id) {
           $mode = 1;
           $rid = $price_id;
       }
       else {
           $mode = 0;
           $rid  = 0;
       }
       $priceRes  = ProductApi::soap()->In_Dynamic_Price_Merge($pid, $pc['start_date'],$pc['end_data'],
           $pc['pg'], $pc['pl'], $pc['ptype'], $mode, $rid, '', $pc['ondays'], $pc['storage']);
       if ($priceRes!=100) {
           ProductApi::writeLog(ProductApi::now()."|价格插入失败.返回{$priceRes}",
               'logs/price.err');
           ProductApi::Response('100');
       }
    }
}

//TODO::最后更新产品表状态
$product->SetTicketState($ticketInsertRet['pid'], (int)$body->status);
ProductApi::Response(200, array(
        'code'      => 200,
        'mode'      => $handlerMode,
        'pid'       => $pid,
        'lid'       => $lid,
        'remote_id' => $remote_id,
    )
);
?>